/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Ui;

import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Font;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.regex.PatternSyntaxException;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.RowFilter;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;

/**
 *
 * @author Esteban
 */
public class PanelAsignarClasePaso3 extends javax.swing.JPanel {

    /**
     * Creates new form PanelAsignarClasePaso3
     */
    public PanelAsignarClasePaso3(JPanel panelCards, CardLayout cards, int anioActual, int mesActual, String mesActual2, int dia, String dia2, int hora_inicio, String hora_inicio2, int hora_fin, String hora_fin2) {
        this.cards=cards;
        this.panelCards=panelCards;
        this.anioActual=anioActual;
        this.mesActual=mesActual;
        this.mesActual2=mesActual2;
        this.dia=dia;
        this.dia2=dia2;
        this.hora_inicio=hora_inicio;
        this.hora_inicio2=hora_inicio2;
        this.hora_fin=hora_fin;
        this.hora_fin2=hora_fin2;
        initComponents();
        initComponents2();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        btnAnterior = new javax.swing.JButton();
        clase = new javax.swing.JLabel();
        scrollClase = new javax.swing.JScrollPane();
        tablaClase = new javax.swing.JTable();
        curso = new javax.swing.JLabel();
        estudiante = new javax.swing.JLabel();
        campoCurso = new javax.swing.JLabel();
        campoEst = new javax.swing.JLabel();
        horario = new javax.swing.JLabel();

        btnAnterior.setFont(new java.awt.Font("Calibri", 0, 14)); // NOI18N
        btnAnterior.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Img/anterior.png"))); // NOI18N
        btnAnterior.setText("Anterior");
        btnAnterior.setToolTipText("Paso anterior");
        btnAnterior.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                btnAnteriorMousePressed(evt);
            }
        });

        clase.setFont(new java.awt.Font("Calibri", 1, 20)); // NOI18N
        clase.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Img/asignar.png"))); // NOI18N
        clase.setText("Asignar Estudiante a Clase Compartida");

        scrollClase.setBackground(new java.awt.Color(255, 255, 255));
        scrollClase.setBorder(javax.swing.BorderFactory.createTitledBorder(new javax.swing.border.LineBorder(new java.awt.Color(153, 153, 153), 1, true), "Seleccione el grupo a asignarle al estudiante", javax.swing.border.TitledBorder.LEFT, javax.swing.border.TitledBorder.TOP, new java.awt.Font("Calibri", 1, 18), new java.awt.Color(0, 153, 254))); // NOI18N

        tablaClase.setFont(new java.awt.Font("Calibri", 0, 14)); // NOI18N
        tablaClase.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Clases Compartidas"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tablaClase.setGridColor(new java.awt.Color(0, 102, 204));
        tablaClase.setSelectionBackground(new java.awt.Color(0, 153, 254));
        tablaClase.getTableHeader().setReorderingAllowed(false);
        scrollClase.setViewportView(tablaClase);

        curso.setFont(new java.awt.Font("Calibri", 0, 14)); // NOI18N
        curso.setText("Curso seleccionado:");

        estudiante.setFont(new java.awt.Font("Calibri", 0, 14)); // NOI18N
        estudiante.setText("Estudiante seleccionado:");

        campoCurso.setFont(new java.awt.Font("Calibri", 0, 14)); // NOI18N

        campoEst.setFont(new java.awt.Font("Calibri", 0, 14)); // NOI18N

        horario.setFont(new java.awt.Font("Calibri", 0, 14)); // NOI18N
        horario.setText("Horario seleccionado:");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(93, 93, 93)
                        .addComponent(scrollClase, javax.swing.GroupLayout.PREFERRED_SIZE, 640, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(349, 349, 349)
                        .addComponent(btnAnterior)))
                .addContainerGap(93, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(0, 0, Short.MAX_VALUE)
                .addComponent(clase)
                .addGap(221, 221, 221))
            .addGroup(layout.createSequentialGroup()
                .addGap(234, 234, 234)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(horario)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(curso)
                                .addGap(39, 39, 39))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addComponent(estudiante)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)))
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(campoEst, javax.swing.GroupLayout.PREFERRED_SIZE, 309, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(campoCurso, javax.swing.GroupLayout.PREFERRED_SIZE, 290, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addGap(0, 0, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(49, 49, 49)
                .addComponent(clase)
                .addGap(18, 18, 18)
                .addComponent(horario)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 11, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(campoCurso, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 17, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(curso, javax.swing.GroupLayout.Alignment.TRAILING))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(campoEst, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(estudiante, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addGap(32, 32, 32)
                .addComponent(scrollClase, javax.swing.GroupLayout.PREFERRED_SIZE, 300, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(36, 36, 36)
                .addComponent(btnAnterior)
                .addGap(31, 31, 31))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void btnAnteriorMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnAnteriorMousePressed
        // TODO add your handling code here:
        anterior();
    }//GEN-LAST:event_btnAnteriorMousePressed

    public void setOpciones(String etqCurso, String etqEst, int codCurso, String cedEst){
        setCurso(etqCurso);
        setEstudiante(etqEst);
        setCodigoCurso(codCurso);
        setCedulaEst(cedEst);
        horario.setText("Horario: "+getDia2()+" "+getHoraInicio2()+" - "+getHoraFin2());
    }
    
    public void setListaPaneles(ArrayList<JPanel> lista){
        paneles=lista;
    }
    
    private void setCurso(String etqCurso){
        campoCurso.setText(etqCurso);
    }
    
    private void setEstudiante(String etqEst){
        campoEst.setText(etqEst);
    }
    
    private void setCodigoCurso(int codigo){
        codigoCurso=codigo;
    }
    
    private void setCedulaEst(String cedEst){
        cedulaEst=cedEst;
    }
    
    public String getEstudiante1(){
        return cedulaEst;
    }
    
    public int getCurso1(){
        return codigoCurso;
    }
    
    public String getEstudiante2(){
        return campoEst.getText();
    }
    
    public String getCurso2(){
        return campoCurso.getText();
    }
    
    public int getAnio(){
        return anioActual;
    }
    
    public int getMes1(){
        return mesActual;
    }
    
    public String getMes2(){
        return mesActual2;
    }
    
    public int getDia1(){
        return dia;
    }
    
    public String getDia2(){
        return dia2;
    }
    
    public int getHoraInicio1(){
        return hora_inicio;
    }
    
    public String getHoraInicio2(){
        return hora_inicio2;
    }
    
    public int getHoraFin1(){
        return hora_fin;
    }
    
    public String getHoraFin2(){
        return hora_fin2;
    }
    
    public void setSuperPanel(JDialog superPanel){
        this.superPanel=superPanel;
    }
    
    private void anterior(){
        cards.previous(panelCards);
    }
    
    private void initComponents2(){
        scrollClase.getViewport().setBackground(Color.WHITE);
        tablaClase.getTableHeader().setFont( new Font( "Calibri" , Font.PLAIN, 16 ));
        tablaClase.setDefaultRenderer(InfoGrupoCompartido.class, new CeldaGrupoCompartido());
        tablaClase.setDefaultEditor(InfoGrupoCompartido.class, new CeldaGrupoCompartido());
        tablaClase.setRowHeight(113);
    }
    
    public void cargarClasesCompartidas(){
        ArrayList<InfoGrupoCompartido> lista = new ArrayList();
        Connection conexion=null;
        Statement sentencia=null;
        ResultSet resultado=null;
        
        try {
            Class.forName("org.postgresql.Driver");
        }catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        try{
            conexion = DriverManager.getConnection(cadenaConexion);
            sentencia = conexion.createStatement();
            String consultaSQL = "select profesor,numero from grupo where anio="+anioActual+" and mes="+mesActual+" and dia="+dia+" and hora_inicio="+hora_inicio+" and hora_fin="+hora_fin+"and activo='true' and curso="+((PanelAsignarClasePaso1)paneles.get(0)).getCursoSeleccionado()+" and modalidad=2 and cant_alumnos=1";
            resultado = sentencia.executeQuery(consultaSQL);
            int clases=0;
            while(resultado.next()){
                clases++;
            }
            
            if(clases!=0){
                Statement sentencia2 = conexion.createStatement();
                ResultSet resultado2 = sentencia2.executeQuery(consultaSQL);
                while(resultado2.next()){
                    
                    Statement sentencia3 = conexion.createStatement();
                    consultaSQL = "select nombre,apellido1,apellido2 from profesor where cedula='"+resultado2.getString("profesor")+"'";
                    ResultSet resultado3 = sentencia3.executeQuery(consultaSQL);
                    String profesor="";
                    while(resultado3.next()){
                        profesor=resultado3.getString("nombre").replaceAll("\\s+","")+" "+resultado3.getString("apellido1").replaceAll("\\s+","");  
                        if(resultado3.getString("apellido2")!=null){
                            profesor=profesor+" "+resultado3.getString("apellido2").replaceAll("\\s+",""); 
                        }
                    }
                    
                    InfoGrupoCompartido grupo = new InfoGrupoCompartido(profesor,resultado2.getInt("numero"),this,superPanel);
                    lista.add(grupo);
                    
                }
            }
                    
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(this, "\n Imposible cargar clases compartidas activas\n Error en la base de datos", "Error", JOptionPane.ERROR_MESSAGE);
            e.printStackTrace();
            conexion = null;
        }
        finally {
            if (resultado != null) {
                try {
                    resultado.close();
                } catch (Exception e) {
                e.printStackTrace();
                }
            }
            if (sentencia != null) {
                try {
                    sentencia.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (conexion != null) {
                try {
                    conexion.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        
        tablaClase.setModel(new GrupoCompartidoTableModel(lista));
        
        
    }
    
    public String acompanianteClase(int curso, int anio, int mes, int numero){
        Connection conexion=null;
        Statement sentencia=null;
        ResultSet resultado=null;
        
        try {
            Class.forName("org.postgresql.Driver");
        }catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        try{
            conexion = DriverManager.getConnection(cadenaConexion);
            sentencia = conexion.createStatement();
        
            String consultaSQL = "select estudiante from matricula where anio="+anio+" and mes="+mes+" and numero="+numero+" and curso="+curso; 
            resultado = sentencia.executeQuery(consultaSQL);
            while(resultado.next()){
                Statement sentencia2;
                ResultSet resultado2;
                sentencia2 = conexion.createStatement();
                consultaSQL = "select cedula,nombre,apellido1,apellido2 from estudiante where cedula='"+resultado.getString("estudiante")+"'"; 
                resultado2 = sentencia2.executeQuery(consultaSQL);
                String acompaniante;
                while(resultado2.next()){
                    acompaniante=resultado2.getString("cedula").replaceAll("\\s+","")+"-"+resultado2.getString("nombre").replaceAll("\\s+","")+" "+resultado2.getString("apellido1").replaceAll("\\s+","");
                    if(resultado2.getString("apellido2")!=null){
                        acompaniante=acompaniante+" "+resultado2.getString("apellido2").replaceAll("\\s+",""); 
                    }
                    return acompaniante;
                }        
            }
                    
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(this, "\n Imposible comprobar si el estudiante ya está matriculado en otros cursos a la misma hora\n Error en la base de datos", "Error", JOptionPane.ERROR_MESSAGE);
            e.printStackTrace();
            conexion = null;
        }
        finally {
            if (resultado != null) {
                try {
                    resultado.close();
                } catch (Exception e) {
                e.printStackTrace();
                }
            }
            if (sentencia != null) {
                try {
                    sentencia.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (conexion != null) {
                try {
                    conexion.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return "";
    }
    
    public class GrupoCompartidoTableModel extends AbstractTableModel {
        ArrayList grupos;
 
        public GrupoCompartidoTableModel(ArrayList grupos) {
            this.grupos = grupos;
        }
        
        public void anadirGrupo(InfoGrupoCompartido panel){
            grupos.add(panel);
        } 
 
        public Class getColumnClass(int columnIndex) { return InfoGrupoCompartido.class; }
        public int getColumnCount() { return 1; }
        public String getColumnName(int columnIndex) { return "Clases compartidas"; }
        public int getRowCount() { return grupos.size(); }
        public Object getValueAt(int rowIndex, int columnIndex) { return (grupos == null) ? null : grupos.get(rowIndex); }
        public boolean isCellEditable(int columnIndex, int rowIndex) { return true; }
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAnterior;
    private javax.swing.JLabel campoCurso;
    private javax.swing.JLabel campoEst;
    private javax.swing.JLabel clase;
    private javax.swing.JLabel curso;
    private javax.swing.JLabel estudiante;
    private javax.swing.JLabel horario;
    private javax.swing.JScrollPane scrollClase;
    private javax.swing.JTable tablaClase;
    // End of variables declaration//GEN-END:variables
    private CardLayout cards;
    private JPanel panelCards;
    private static final String cadenaConexion = "jdbc:postgresql://localhost/SMAAMDB?" + "user=postgres&password=root";
    private ArrayList<JPanel> paneles;
    private JDialog superPanel;
    private int anioActual;
    private int mesActual;
    private String mesActual2;
    private int dia;
    private String dia2;
    private int hora_inicio;
    private String hora_inicio2;
    private int hora_fin;
    private String hora_fin2;
    private String cedulaEst;
    private int codigoCurso;
}
